package com.eostoken.eos_wallet.ui.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.EOSPrice;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.eosnet.common.Params;
import com.eostoken.eos_wallet.helper.DialogConfirmListener;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.mode.AppsModel;
import com.eostoken.eos_wallet.mvp.presenter.AppsPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.AppsView;
import com.eostoken.eos_wallet.utils.CashierInputFilter;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.layout.QMUIRelativeLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.math.BigDecimal;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.BALANCE;
import static com.eostoken.eos_wallet.utils.Constants.EOSIO_TOKEN_CONTRACT_CODE;
import static com.eostoken.eos_wallet.utils.Constants.MGP_SYMBOL;
import static com.eostoken.eos_wallet.utils.Constants.PRICE;
import static com.eostoken.eos_wallet.utils.Constants.TRANSFER_ACTION;
import static com.eostoken.eos_wallet.utils.Constants.contractAddress;

public class MiningMortgageFragment extends BaseFragment<AppsModel, AppsView, AppsPresenterImpl> implements AppsView {

    @BindView(R.id.topBar)
    QMUITopBar topBar;
    @BindView(R.id.walletIconTv)
    QMUIRadiusImageView walletIconTv;
    @BindView(R.id.walletNameTv)
    AppCompatTextView walletNameTv;
    @BindView(R.id.walletAccountTv)
    AppCompatTextView walletAccountTv;
    @BindView(R.id.walletInfoLayout)
    QMUIRelativeLayout walletInfoLayout;
    @BindView(R.id.orderValueTv)
    AppCompatTextView orderValueTv;
    @BindView(R.id.layout1)
    RelativeLayout layout1;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.orderStarTv)
    AppCompatTextView orderStarTv;
    @BindView(R.id.layout2)
    RelativeLayout layout2;
    @BindView(R.id.layout)
    QMUILinearLayout layout;
    @BindView(R.id.nextstepBtn)
    QMUIRoundButton nextstepBtn;
    @BindView(R.id.quantityTitleTv)
    AppCompatTextView quantityTitleTv;
    @BindView(R.id.quantityEt)
    AppCompatEditText quantityEt;
    @BindView(R.id.balanceTv)
    AppCompatTextView balanceTv;

    private String type;
    private MgpWallet wallet;
    private String remaining = "";
    private Bundle bundle;
    private boolean isRemaining;
    private BigDecimal balance;
    private BigDecimal price = BigDecimal.ZERO;
    private BigDecimal quantityMGP;
    private String orderStar;
    private QMUIDialog qmuiDialog;
    private BigDecimal mgpNum;
    private BigDecimal bdMGPValue;
    private String code;
    private String action;
    private String accountName;
    private int mRadius;
    private boolean isMortgage;

//    private static class LazyHolder {
//        private static final MiningMortgageFragment INSTANCE = new MiningMortgageFragment();
//    }
//
//    public static final MiningMortgageFragment getInstance(Bundle bundle) {
//        LazyHolder.INSTANCE.setArguments(bundle);
//        return LazyHolder.INSTANCE;
//    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_mortgage_mining;
    }

    @Override
    protected void initData() {
        wallet = WalletUtils.getCurrentWallet(getActivity());
        bundle = getArguments();
        type = bundle.getString("type", "");
        isMortgage = bundle.getBoolean("isMortgage");
        String mMgpNum = bundle.getString("mgpNum", "0");
        if (ObjectUtils.isEmpty(mMgpNum)) {
            mMgpNum = "0";
        }
        mgpNum = new BigDecimal(mMgpNum);
        accountName = wallet.getCurrentAccountName();
        mRadius = QMUIDisplayHelper.dp2px(getContext(), 8);
        presenter.requestCurrencyBalance(Params.getBalancePamars(accountName, EOSIO_TOKEN_CONTRACT_CODE, MGP_SYMBOL));
        presenter.requestPortData(Constants.PRICE_MGP, PRICE);

    }

    @Override
    protected void initView(View contentView) {
        topBar.setTitle(type);
        topBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popOrFinish();
            }
        });
        if (isMortgage) {
            quantityTitleTv.setText(getString(R.string.str_mortgage_initiated));
            layout1.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
            layout2.setVisibility(View.VISIBLE);
            balanceTv.setVisibility(View.VISIBLE);
            isRemaining = false;
            remaining = "";
        } else {
            quantityTitleTv.setText(getString(R.string.str_callable_quantity));
            remaining = bundle.getString("remaining", "");
            setEditableEditText(quantityEt, false);
            layout1.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
            layout2.setVisibility(View.GONE);
            balanceTv.setVisibility(View.GONE);
            isRemaining = true;
        }
        if (ObjectUtils.isEmpty(remaining)) {
            remaining = "";
        }

        walletInfoLayout.setRadius(mRadius);
        walletNameTv.setText(wallet.getWalletName());
        walletAccountTv.setText(accountName);

        quantityEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!ObjectUtils.isEmpty(s)) {
                    quantityMGP = new BigDecimal(s.toString());
                    mgpValueView();
                    if (bdMGPValue.compareTo(new BigDecimal("5000")) >= 0) {
                        orderStar = "M4";
                    } else if (bdMGPValue.compareTo(new BigDecimal("2000")) >= 0) {
                        orderStar = "M3";
                    } else if (bdMGPValue.compareTo(new BigDecimal("500")) >= 0) {
                        orderStar = "M2";
                    } else if (bdMGPValue.compareTo(new BigDecimal("100")) >= 0) {
                        orderStar = "M1";
                    } else {
                        orderStar = "M0";
                    }
                    orderStarTv.setText(orderStar);
                }
            }
        });
        InputFilter[] filters = {new CashierInputFilter()};
        quantityEt.setFilters(filters);

    }

    private void mgpValueView() {
        if (quantityMGP == null) {
            quantityMGP = BigDecimal.ZERO;
        }
        bdMGPValue = (mgpNum.add(quantityMGP)).multiply(price).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        String MGPValue = bdMGPValue.toPlainString();
        orderValueTv.setText("$" + MGPValue);
    }

    @Override
    public AppsModel createModel() {
        return new AppsModel();
    }

    @Override
    public AppsView createView() {
        return this;
    }

    @Override
    public AppsPresenterImpl createPresenter() {
        return new AppsPresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    @OnClick(R.id.nextstepBtn)
    public void onViewClicked() {
        String quantity = quantityEt.getText().toString();
        if (ObjectUtils.isEmpty(quantity)) {
            ToastUtils.showLong(R.string.str_cannot_empty);
            return;
        }
        // 如果指定的数与参数相等返回0。
        // 如果指定的数小于参数返回 -1。
        // 如果指定的数大于参数返回  1。
        BigDecimal bdQuantity = new BigDecimal(quantity.trim());
        if (isMortgage && bdMGPValue.compareTo(new BigDecimal(100)) < 0) {
            ToastUtils.showLong(R.string.str_cant_less_than_100);
            return;
        }
        if (isMortgage && bdQuantity.compareTo(balance) > 0) {
            ToastUtils.showLong(R.string.str_cannot_greater_balance);
        } else {
            if (qmuiDialog == null) {
                qmuiDialog = DialogHelper.showEditTextDialog(getActivity(), getString(R.string.str_password_authentification),
                        getString(R.string.str_enter_password), getString(android.R.string.ok), getString(android.R.string.cancel), listener, true);
            }
            qmuiDialog.show();
        }
    }

    DialogConfirmListener listener = new DialogConfirmListener() {
        @Override
        public void onClick(QMUIDialog dialog, View view, int index) {
            dialog.dismiss();
            EditText editText = (EditText) view;
            String contrastPassword = editText.getText().toString().trim();
            if (ObjectUtils.equals(contrastPassword, wallet.getWalletPassword())) {
                transferTransaction();
            } else {
                ToastUtils.showShort(StringUtils.getString(R.string.str_wrong_password));
            }
            editText.setText("");
        }
    };

    private void transferTransaction() {
        Map params = MapUtils.newHashMap();
        if (isRemaining) {
            action = "redeem";
            code = contractAddress;
            params.put("account", accountName);
        } else {
            BigDecimal bdQuantity = new BigDecimal(quantityEt.getText().toString().trim());
            String quantity = bdQuantity.setScale(4, BigDecimal.ROUND_HALF_DOWN).toPlainString();
//        String memo = type;
            code = EOSIO_TOKEN_CONTRACT_CODE;
            action = TRANSFER_ACTION;
            params.put("memo", "staking");
            params.put("from", accountName);
            params.put("to", contractAddress);
            params.put("quantity", String.format(StringUtils.getString(R.string.str_balance_unit_blank), quantity));
        }
        String jsonData = "";
        if (ObjectUtils.isNotEmpty(params)) {
            jsonData = GsonUtils.toJson(params);
        }
        presenter.sendTransaction(action, wallet.getPrivateKey(), accountName, code, jsonData);
    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case BALANCE://["161.4881 MGP"]
                String b = "0";
                if (!ObjectUtils.isEmpty(data)) {
                    if (data.toString().contains("MGP")) {
                        b = data.toString().split(" ")[0].replace("[\"", "");
                    }
                }
                balance = new BigDecimal(b);
                balanceTv.setText(String.format(StringUtils.getString(R.string.str_balance), balance.toPlainString()));
                break;
            case PRICE:
                if (data != null) {
                    EOSPrice eosPrice = (EOSPrice) data;
                    EOSPrice.DataBean dataBean = eosPrice.getData();
                    price = dataBean.getPrice();
                }
                if (price == null) {
                    price = BigDecimal.ZERO;
                }
                mgpValueView();
                break;
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case BALANCE://["161.4881 MGP"]
                if (balance == null) {
                    balance = BigDecimal.ZERO;
                    balanceTv.setText(String.format(StringUtils.getString(R.string.str_balance), balance.toPlainString()));
                }
                break;
            case PRICE:
                if (price == null) {
                    price = BigDecimal.ZERO;
                }
                break;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (qmuiDialog != null) {
            if (qmuiDialog.isShowing()) {
                qmuiDialog.dismiss();
            }
        }
        qmuiDialog = null;
        quantityEt.setText("");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isMortgage)
            quantityEt.setText(remaining);
    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {
        if (success) {
            ToastUtils.showShort(R.string.str_transaction_success);
            popOrFinish();
        } else {
            ToastUtils.showShort(o1.toString());
        }
    }

    public void setEditableEditText(AppCompatEditText editText, boolean isEnabled) {
        editText.setEnabled(isEnabled);//去掉点击时编辑框下面横线:
        editText.setFocusable(isEnabled);//不可编辑
        editText.setFocusableInTouchMode(isEnabled);//不可编辑
    }
}
